/** 
 * Project Name:jd-orm 
 * File Name:DatasourceConfiguration.java 
 * Package Name:com.jd.orm.framework.configuration 
 * Date:2014-5-12下午7:15:37 
 * Copyright (c) 2014, liubing1@jd.com All Rights Reserved. 
 * 
 */

package com.jd.orm.framework.configuration;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.jd.orm.framework.configuration.bean.ConfigurationBean;
import com.jd.orm.framework.configuration.bean.ConfigurationDatasourceBean;
import com.jd.orm.framework.core.exception.DbError;
import com.jd.orm.framework.core.exception.SysError;
import com.jd.orm.framework.core.exception.SystemException;
import com.thoughtworks.xstream.XStream;

/**
 * ClassName: DatasourceConfiguration <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * date: 2014-5-12 下午7:15:37 <br/>
 * 
 * @author liubing1@jd.com
 * @version
 * @since up JDK 1.5
 */

public class DatasourceConfiguration {
	/**
	 * 
	 * getConfigurationBean: <br/>
	 * xml 转化为javabean<br/>
	 * 
	 * @author liubing1@jd.com
	 * @param xml
	 * @return
	 * @throws Exception
	 * @since JDK 1.5
	 */
	public static ConfigurationBean getConfigurationBean(String xml) {
		try {
			String content = readFile(xml);
			XStream stream = new XStream();
			stream.alias("configuration", ConfigurationBean.class);
			stream.aliasField("datasources", ConfigurationBean.class,
					"configurationDatasourceBeans");
			stream.alias("datasource", ConfigurationDatasourceBean.class);

			stream.useAttributeFor(ConfigurationDatasourceBean.class,
					"datasourceId");
			stream.aliasAttribute(ConfigurationDatasourceBean.class,
					"datasourceId", "id");
			ConfigurationBean configurationBean = (ConfigurationBean) stream
					.fromXML(content);
			return configurationBean;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw SystemException.unchecked(e, DbError.IO_ERROR);
		}
	}

	/**
	 * 
	 * readFile: <br/>
	 * get content from file<br/>
	 * 
	 * @author liubing1@jd.com
	 * @param fileName
	 * @return
	 * @throws Exception
	 * @since JDK 1.5
	 */
	public static String readFile(String fileName) {
		try {
			String fileContent = "";
			File f = new File(fileName);
			FileReader  fileReader = new FileReader(f);
			BufferedReader reader = new BufferedReader(fileReader);
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent = fileContent + line;
			}
			reader.close();
			return fileContent;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			throw SystemException.unchecked(e, SysError.FILE_NOT_FOUND);
		}catch (IOException e) {
			// TODO Auto-generated catch block
			throw SystemException.unchecked(e, DbError.IO_ERROR);
		}
	}

}
